(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:HuodongCtrl
     * @description
     * # HuodongCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('HuodongCtrl', HuodongCtrl);

    HuodongCtrl.$inject = ['$scope', 'dataService', 'helper', '$rootScope', '$location', 'sessionService', '$interval', '$state'];

    function HuodongCtrl($scope, dataService, helper, $rootScope, $location, sessionService, $interval, $state) {

        //报名活动列表
        $scope.listAction = function() {
            $scope.pageSize = 10;
            $scope.getList(1);
            $scope.signHuoDongList = {};
            $scope.$on('event:up-store-id', function() {
                $scope.getList(1);
            });
        }

        $scope.getList = function(pageNo) {
            var query = {
                content: {
                    page_no: pageNo,
                    page_size: $scope.page_Size ? $scope.page_Size : 10,
                    store_id: $rootScope.store_id,
                    all: 1
                }
            };

            dataService.huodongGet(query).then(function(list) {
                if (list) {
                    $scope.huodong_list = list.huodong_list;
                    $scope.total_count = list.total_count;
                }
            });
        }

        //签到所需要的活动数组
        $scope.signAdd = function(huodongData) {
            // $scope.signHuoDongList
            var list = {
                "huodong_id": huodongData.huodong_id,
                "name": huodongData.name,
                "huodong_start_time": huodongData.huodong_start_time,
                "huodong_end_time": huodongData.huodong_end_time
            };

            $scope.signHuoDongList[list.huodong_id] = list;
            $scope.obj();
        }

        $scope.obj = function() {
            $scope.signHuoDongAry = _.values($scope.signHuoDongList);
        }

        $scope.signAdd1 = function() {
            var huodong_ids = _.pluck($scope.signHuoDongAry, "huodong_id");

            location.href = "#/huodong/sign?huodong_ids=" + huodong_ids.join(",");
        }

        //添加页面
        $scope.addAction = function() {
            $scope.huodong_id = $location.search().huodong_id;

            if ($scope.huodong_id) {
                getOneData();
                $scope.$on('event:up-store-id', function() {
                    getOneData();
                });
            } else {
                $scope.huodong_data = {
                    "store_id": $rootScope.store_id,
                    "name": "报名活动",
                    "img": "",
                    "img1": "",
                    "img2": "",
                    "img3": "",
                    "img4": "",
                    "start_time": $scope.getDateStr(0),
                    "end_time": $scope.getDateStr(1),
                    "huodong_start_time": $scope.getDateStr(0),
                    "huodong_end_time": $scope.getDateStr(1),
                    "pay_amount": 100,
                    "original_price": 200,
                    "need_customer_num": 100,
                    "limit_num": 1,
                    "introduce": "活动说明",
                    "payed_out": "",
                    "remark": "",
                    "custom_form_id": -1
                };
            }
        }

        //活动添加
        $scope.huodongAdd = function() {
            if ($scope.huodong_data.end_time < $scope.huodong_data.start_time) {
                helper.myAlert("报名结束时间不能小于报名开始时间");
                return false;
            }

            if ($scope.huodong_data.huodong_end_time < $scope.huodong_data.huodong_start_time) {
                helper.myAlert("活动结束时间不能小于活动开始时间");
                return false;
            }

            if ($scope.huodong_data.need_customer_num <= 1 || !$scope.huodong_data.need_customer_num) {
                helper.myAlert("参会人数最少两个人");
                return false;
            }

            if (!$scope.huodong_data.original_price) {
                helper.myAlert("报名费原价不能为空！");
                return false;
            }

            if (parseFloat($scope.huodong_data.pay_amount) > parseFloat($scope.huodong_data.original_price)) {
                helper.myAlert("现报名费必须小于原价");
                return false;
            }

            if ($scope.huodong_data.pay_amount < 0) {
                helper.myAlert("报名费价格不能为负值！");
                return false;
            }

            if ($scope.huodong_data.limit_num < 1) {
                helper.myAlert("报名次数不能少于1次！");
                return false;
            }

            if ($scope.huodong_id) {
                dataService.huodongUpdate($scope.huodong_data).then(function(result) {
                    if (result.huodong_id) {
                        helper.myAlert("success", "#/huodong/list");
                    } else {
                        helper.myAlert(result.errmsg);
                    }
                });
            } else {
                dataService.huodongAdd($scope.huodong_data).then(function(result) {
                    if (result.huodong_id) {
                        helper.myAlert("success", "#/huodong/list");
                    } else {
                        helper.myAlert(result.errmsg);
                    }
                });
            }
        }

        //单个报名活动数据
        function getOneData() {
            var query = {
                content: {
                    huodong_id: $scope.huodong_id,
                    store_id: $rootScope.store_id,
                }
            };

            dataService.huodongGet(query).then(function(result) {
                if (result.huodong_list) {
                    $scope.huodong_data = result.huodong_list[0];
                    $scope.huodong_data.introduce = json2html(JSON.parse($scope.huodong_data.introduce));
                    $scope.huodong_data.payed_out = json2html(JSON.parse($scope.huodong_data.payed_out));
                    $scope.huodong_data.need_customer_num = parseFloat($scope.huodong_data.need_customer_num);
                    $scope.huodong_data.limit_num = parseFloat($scope.huodong_data.limit_num);

                }
            });
        }

        //活动时间计算
        $scope.getDateStr = function(addDayCount) {
            var dd = new Date();
            dd.setDate(dd.getDate() + addDayCount);
            var y = dd.getFullYear();
            var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);
            var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
            var h = dd.getHours();
            var i = dd.getMinutes();
            var s = dd.getSeconds();

            if (i < 10) {
                i = "0" + i;
            }
            var s = dd.getSeconds();
            if (s < 10) {
                s = "0" + s;
            }
            return y + "-" + m + "-" + d + " " + h + ":" + i + ":" + s;
        }

        //报名活动详情列表
        $scope.detailAction = function() {
            $scope.pageSize = 10;
            $scope.huodong_id = $location.search().huodong_id;
            $scope.chosedStatus = "all";

            $scope.getDetail1(1);
            getOneData();
        }

        $scope.getDetail1 = function(pageNo) {
            var query = {
                content: {
                    page_no: pageNo,
                    page_size: $scope.page_Size ? $scope.page_Size : 10,
                    store_id: $rootScope.store_id,
                    huodong_id: $scope.huodong_id,
                }
            };

            if ($scope.chosedStatus && $scope.chosedStatus != "all") {
                if ($scope.chosedStatus == "weizhifu") {
                    query.content.status = 1;
                }
                if ($scope.chosedStatus == "yizhifu") {
                    query.content.status = 2;
                }
                if ($scope.chosedStatus == "yiqiandao") {
                    query.content.status = 3;
                }
                if ($scope.chosedStatus == "zuofei") {
                    query.content.status = 10;
                }
            }

            if ($scope.sn) {
                query.content.sn = $scope.sn;
            }

            if ($scope.mobile) {
                query.content.mobile = $scope.mobile;
            }

            dataService.huodongDetailGet(query).then(function(list) {
                if (list) {
                    $scope.detail_list = list.detail_list;
                    $scope.detail_count11 = list.detail_count;
                }
            });
        }

        //签到页面
        $scope.signAction = function() {
            $scope.huodong_ids = $location.search().huodong_ids;
            if (!$scope.huodong_ids) {
                return helper.myAlert("请选择要签到的活动", "#huodong/list");
            }
            $scope.$watch('wxappid', function(newValue, oldValue, scope) {
                if (newValue) {
                    $scope.wxappid = newValue;
                    //生成二维码
                    $scope.createQrcode();
                }
            }, true);
        }

        var time_code;
        $scope.createQrcode = function() {
            $scope.sonFunc();

            $interval.cancel(time_code);
            //5分钟刷新一次
            time_code = $interval(function() {
                $scope.sonFunc();
            }, 300 * 1000, time_code);
        }

        $scope.sonFunc = function() {
            $scope.secret_key = helper.guid24();
            // $scope.secret_key = "0edaa0cbb186f4ed40d6aa50";
            // console.log("秘钥",$scope.secret_key);

            $scope.sceneSave().then(function(result) {
                if (!result) {
                    return helper.myAlert("出错了！请重试");
                }
                dataService.acodeunlimitGet($scope.wxappid, "HDQD" + $scope.secret_key, true, "pages/index/index", false, 300).then(function(r) {
                    if (!r) {
                        helper.myAlert("error");
                    } else {
                        $scope.dataimage = "data:image/png;base64," + r;

                        //数据清空
                        $scope.detail_data = {};
                        $scope.huodong_data = {};
                        //3秒刷新 是否有用户已经签到
                        $scope.checkSign();
                    }
                });
            });
        }

        $scope.sceneSave = function() {
            return dataService.sceneSave($scope.secret_key, $scope.huodong_ids.split(",")).then(function(result) {
                // console.error('scene-->', result);
                return result;
            });
        }

        var timeId;
        //判断是否有用户已经签到
        $scope.checkSign = function() {
            $scope.sonCheckSign();

            timeId = $interval(function() {
                $scope.sonCheckSign(timeId);
            }, 3000, timeId);
        }

        $scope.sonCheckSign = function(timeId) {
            var query = {
                content: {
                    "store_id": $rootScope.store_id,
                    "secret_key": $scope.secret_key
                }
            };
            dataService.huodongDetailGet(query).then(function(result) {
                $scope.hadScaned = result.hadScaned;

                if (result.detail_count) {
                    $scope.detail_data = result.detail_list[0];
                    if ($scope.detail_data) {
                        //查询活动详情
                        $scope.hongdong_id = $scope.detail_data.huodong_id;
                        getOneData();

                        $interval.cancel(timeId);
                    }
                }
            });
        }

        //页面离开，清理interval
        $scope.$on('$destroy', function() {
            $interval.cancel(timeId);
            $interval.cancel(time_code);
        });

        //确认签到
        $scope.signUpdate = function() {
            var query = {
                content: {
                    "detail_id": $scope.detail_data.detail_id,
                }
            };

            dataService.huodongDetailUpdate(query).then(function(result) {
                if (result.detail_id) {
                    $scope.refreshData();
                } else {
                    helper.myAlert("error：" + result.errmsg);
                }
            });
        }

        $scope.getMember = function(iamurl, nick) {
            $scope.iamurl = iamurl;
            $scope.nick = nick;
        }

        //刷新
        $scope.refreshData = function() {
            //二维码
            $scope.createQrcode();

            //数据清空
            $scope.detail_data = {};
            $scope.huodong_data = {};
        }
    }
})();